package net.hvacapp.cmvrfforandroid.ui.selections;

import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.util.Base64;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.SearchView;

import com.alibaba.fastjson.JSON;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.mirror.android.common.util.StringUtils;

import net.hvacapp.cmvrfforandroid.AppException;
import net.hvacapp.cmvrfforandroid.R;
import net.hvacapp.cmvrfforandroid.adapter.BaseAdapterHelper;
import net.hvacapp.cmvrfforandroid.adapter.QuickAdapter;
import net.hvacapp.cmvrfforandroid.constant.Constant;
import net.hvacapp.cmvrfforandroid.http.BasicHttpClient;
import net.hvacapp.cmvrfforandroid.http.HttpCallbackHandle;
import net.hvacapp.cmvrfforandroid.http.HttpConstant;
import net.hvacapp.cmvrfforandroid.model.UserProfileData;
import net.hvacapp.cmvrfforandroid.ui.BaseActivity;
import net.hvacapp.cmvrfforandroid.ui.selections.model.AdministratorDataResp;
import net.hvacapp.cmvrfforandroid.ui.selections.model.BranchCompanyDataResp;
import net.hvacapp.cmvrfforandroid.widget.IOSAlertView;

import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.Background;
import org.androidannotations.annotations.EActivity;
import org.androidannotations.annotations.UiThread;
import org.androidannotations.annotations.ViewById;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

@EActivity(R.layout.activity_selection_parent)
public class SelectionParentActivity extends BaseActivity {

    @ViewById(R.id.lv_branch_company)
    PullToRefreshListView mBranchCompanyLv;
    @ViewById(R.id.sv_branch)
    SearchView mSearchView;

    private QuickAdapter<UserProfileData> mQuickAdapter;

    private boolean mIsMultipleSelection;
    private ArrayList<UserProfileData> mSelectedData;
    private ArrayList<UserProfileData> mDataSource;

    private Dialog mProgressDlg;

    private int beginIndex = 0;
    private int endIndex = 0;
    private String mSearchText;


    /**
     * 页面加载完后执行
     */
    @AfterViews
    @Override
    protected void viewDidLoad() {
        super.viewDidLoad();
        initEvent();
    }

    /**
     * 初始化
     */
    @Override
    public void initBoot() {
        mDataSource = new ArrayList<>();
        mSearchView.setIconifiedByDefault(true);
//        mSearchView.onActionViewExpanded();
        mSearchView.setFocusable(true);
//        mSearchView.clearFocus();
        mSearchView.setSubmitButtonEnabled(true);
        if (mQuickAdapter == null){
            mQuickAdapter = new QuickAdapter<UserProfileData>(context, R.layout.two_lines_cell_item) {
                @Override
                protected void convert(BaseAdapterHelper helper, UserProfileData item) {
                    if (item.getIsSelected() == 1) {
                        helper.setVisible(R.id.iv_selected_mark, true);
                    }
                    else {
                        helper.setVisible(R.id.iv_selected_mark, false);
                    }
                    helper.setText(R.id.tv_title, item.getUserName());
                    helper.setText(R.id.tv_description, item.getName());
                }
            };
        }

        mBranchCompanyLv.setAdapter(mQuickAdapter);
    }

    /**
     * 初始化数据
     */
    @Override
    public void initData(Intent intent) {
        mIsMultipleSelection = intent.getBooleanExtra("multiple", false);
        mSelectedData = intent.getParcelableArrayListExtra("parent");

        beginIndex = 0;
        endIndex = Constant.PAGE_COUNT - 1;
        loadAllCompanysData(beginIndex, endIndex);
    }

    /**
     * 页面名称
     */
    @Override
    public String getName() {
        return "";
    }

    private void initEvent() {
        mSearchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
            @Override
            public boolean onQueryTextSubmit(String query) {
                mSearchText = query;
                beginIndex = 0;
                endIndex = Constant.PAGE_COUNT - 1;
                if (StringUtils.isEmpty(mSearchText)) {
                    loadAllCompanyDataBySearch(beginIndex, endIndex, mSearchText);
                }
                else {
                    loadAllCompanysData(beginIndex, endIndex);
                }
                return true;
            }

            @Override
            public boolean onQueryTextChange(String newText) {
                String def = newText;
                return false;
            }
        });

        mSearchView.setOnCloseListener(new SearchView.OnCloseListener() {
            @Override
            public boolean onClose() {
                mSearchText = "";
                beginIndex = 0;
                endIndex = Constant.PAGE_COUNT - 1;
                if (StringUtils.isEmpty(mSearchText)) {
                    loadAllCompanyDataBySearch(beginIndex, endIndex, mSearchText);
                }
                else {
                    loadAllCompanysData(beginIndex, endIndex);
                }
                return false;
            }
        });

        mBranchCompanyLv.setOnRefreshListener(
                new PullToRefreshBase.OnRefreshListener<ListView>() {
                    @Override
                    public void onRefresh(PullToRefreshBase<ListView> refreshView) {
                        // loadAccountDynamicData();
                        // 下拉刷新
                        if (refreshView.getCurrentMode().equals(PullToRefreshBase.Mode.PULL_FROM_START)) {
                            // 下拉刷新
                            beginIndex = 0;
                            endIndex = Constant.PAGE_COUNT - 1;
                            if (StringUtils.isEmpty(mSearchText)) {
                                loadAllCompanyDataBySearch(beginIndex, endIndex, mSearchText);
                            }
                            else {
                                loadAllCompanysData(beginIndex, endIndex);
                            }
                        } else {
                            // 上拉加载更多
                            beginIndex = mQuickAdapter.getCount();
                            endIndex = beginIndex + Constant.PAGE_COUNT - 1;
                            if (StringUtils.isEmpty(mSearchText)) {
                                loadAllCompanyDataBySearch(beginIndex, endIndex, mSearchText);
                            }
                            else {
                                loadAllCompanysData(beginIndex, endIndex);
                            }
                        }
                    }
                }

        );

        mBranchCompanyLv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                UserProfileData data = (UserProfileData) parent.getItemAtPosition(position);

                if (mIsMultipleSelection) {
                    ImageView ivSelectMark = (ImageView) view.findViewById(R.id.iv_selected_mark);
                    if (data.getIsSelected() == 1) {
                        data.setIsSelected(0);
                        ivSelectMark.setVisibility(View.INVISIBLE);
                    } else {
                        data.setIsSelected(1);
                        ivSelectMark.setVisibility(View.VISIBLE);
                    }
                    resetSelectedData(data);
                } else {

                    if (mSelectedData == null) {
                        mSelectedData = new ArrayList<>();
                    }
                    else {
                        mSelectedData.clear();
                    }
                    mSelectedData.add(data);
                    Intent intent = new Intent();
                    Bundle bundle = new Bundle();
                    bundle.putParcelableArrayList("parent", mSelectedData);
                    intent.putExtras(bundle);
                    setResult(RESULT_OK, intent);
                    finish();
                }
            }
        });
    }


    private void loadAllCompanyDataBySearch(final int begin, int end, String searchText) {

        Map<String, Object> param = new HashMap<>();
        param.put("si", begin);
        param.put("ei", end);
        param.put("kw", searchText);
        param.put("rn", "BranchCompanyAndReseller");

        if (mProgressDlg == null) {
            mProgressDlg = createProgressBarDialog(this, "数据加载中...");
        }
        mProgressDlg.show();

        BasicHttpClient.httpGetAsync(HttpConstant.HTTP_GET_SEARCH_PARENT_COMPANY, param, new HttpCallbackHandle<BranchCompanyDataResp>() {
            @Override
            public void onSuccess(BranchCompanyDataResp obj) {
                // 成功
                mProgressDlg.dismiss();
                mBranchCompanyLv.onRefreshComplete();
                if (begin == 0) {
                    mQuickAdapter.clear();
                }
                if (mSelectedData != null && mSelectedData.size() > 0) {
                    if (obj.getSearchUserProfilesbyRoleResult().size() > 0) {
                        for (int i = 0; i < obj.getSearchUserProfilesbyRoleResult().size(); i++) {
                            UserProfileData item = obj.getSearchUserProfilesbyRoleResult().get(i);
                            for (int j = 0; j < mSelectedData.size(); j++) {
                                if (StringUtils.isEquals(item.getUserName(), mSelectedData.get(j).getUserName())) {
                                    item.setIsSelected(1);
                                    break;
                                }
                            }
                            mQuickAdapter.add(item);

                        }
                    }
                } else {
                    if (obj.getSearchUserProfilesbyRoleResult().size() > 0) {
                        mQuickAdapter.addAll(obj.getSearchUserProfilesbyRoleResult());
                    }
                }
            }

            @Override
            public void onFailure(String response) {
                mBranchCompanyLv.onRefreshComplete();
                mProgressDlg.dismiss();
                showMessage("数据加载失败");
            }

        });
    }


    private void loadAllCompanysData(final int begin, int end) {

        Map<String, Object> param = new HashMap<>();
        param.put("si", begin);
        param.put("ei", end);

        if (mProgressDlg == null) {
            mProgressDlg = createProgressBarDialog(this, "数据加载中...");
        }
        mProgressDlg.show();

        BasicHttpClient.httpGetAsync(HttpConstant.HTTP_GET_ALL_COMPANYS, param, new HttpCallbackHandle<BranchCompanyDataResp>() {
            @Override
            public void onSuccess(BranchCompanyDataResp obj) {
                // 成功
                mProgressDlg.dismiss();
                mBranchCompanyLv.onRefreshComplete();
                if (begin == 0) {
                    mQuickAdapter.clear();
                }
                if (mSelectedData != null && mSelectedData.size() > 0) {
                    if (obj.getGetBranchCompanyAndResellerUserProfilesResult().size() > 0) {
                        for (int i = 0; i < obj.getGetBranchCompanyAndResellerUserProfilesResult().size(); i++) {
                            UserProfileData item = obj.getGetBranchCompanyAndResellerUserProfilesResult().get(i);
                            for (int j = 0; j < mSelectedData.size(); j++) {
                                if (StringUtils.isEquals(item.getUserName(), mSelectedData.get(j).getUserName())) {
                                    item.setIsSelected(1);
                                    break;
                                }
                            }
                            mQuickAdapter.add(item);
                        }
                    }
                } else {
                    if (obj.getGetBranchCompanyAndResellerUserProfilesResult().size() > 0) {
                        mQuickAdapter.addAll(obj.getGetBranchCompanyAndResellerUserProfilesResult());
                    }
                }
            }

            @Override
            public void onFailure(String response) {
                mBranchCompanyLv.onRefreshComplete();
                mProgressDlg.dismiss();
                showMessage("数据加载失败");
            }

        });
    }


    private void resetSelectedData(UserProfileData data) {
        if (data.getIsSelected() == 1) {
            if (mSelectedData == null) {
                mSelectedData = new ArrayList<>();
            }
            boolean hasSame = false;
            for (UserProfileData item : mSelectedData) {
                if (StringUtils.isEquals(data.getUserName(), item.getUserName())) {
                    hasSame = true;
                    break;
                }
            }
            if (!hasSame) {
                mSelectedData.add(data);
            }
        }
        else {
            if (mSelectedData != null && mSelectedData.size() > 0) {
                for (UserProfileData item : mSelectedData) {
                    if (StringUtils.isEquals(data.getUserName(), item.getUserName())) {
                        mSelectedData.remove(item);
                        break;
                    }
                }
            }
        }
    }
}

